#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <stdio.h>
#include <netinet/in.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <netdb.h>


/* http://pan.baidu.com/share/qrcode?w=150&h=150&url=今天是个好日子 */

#define HTTP_REQ "GET /share/qrcode?w=200&h=200&url=今天是个好日子 HTTP/1.1\r\nHost: pan.baidu.com\r\nConnection: close\r\n\r\n"

int main(void)
{
	//1.连接服务器
	int sockfd = socket(AF_INET, SOCK_STREAM, 0);
	if(sockfd < 0)
	{
		return -1;		
	}
	
	struct hostent *host = gethostbyname("pan.baidu.com");
	if(host == NULL)
	{
		perror("not find");
		return -1;
	}
	if(host->h_addr_list[0] == NULL)
	{
		printf("域名解析失败\n");
		return -1;
	}
	struct in_addr in = {*((int *)(host->h_addr_list[0]))};   //获取到IP
	struct sockaddr_in saddr;
	bzero(&saddr, sizeof(saddr));
	saddr.sin_family = AF_INET;
	saddr.sin_port = htons(80);                      //服务器端口号
	saddr.sin_addr.s_addr = inet_addr(inet_ntoa(in));//服务器地址

	int ret = connect(sockfd, (struct sockaddr*)&saddr, sizeof(saddr));
	if(ret < 0)
	{
		perror("connect fail");
	}
	
	//2.发送http请求
	write(sockfd, HTTP_REQ, strlen(HTTP_REQ));
	
	
	//3.接收服务器应答数据
	char buffer[2024]={0};
	ret  = read(sockfd, buffer, 2024);
	char buf[20];
	bzero(buf,20);
	char *a = strstr(buffer,"Content-Length: ")+strlen("Content-Length: ");
	sscanf(a,"%[^\n]",buf);                  //从字符串取出到\n之前的信息
	printf("**********************%s\n",buf);

	printf("alllen=%d\n",ret);
  	printf("filesize%s\n",buffer);	
	char *p = strstr(buffer, "\r\n\r\n")+4;  //http是以\r\n\r\n为结尾
	FILE *file = fopen("./my.png", "w+");
	
	fwrite(p, ret-(p-buffer), 1, file);
	fclose(file);
	
	return 0;
}
